package com.key.win.business.chat.ctrl;

import com.key.win.base.auth.AuthenticationUtil;
import com.key.win.base.util.BeanUtils;
import com.key.win.base.util.DateUtils;
import com.key.win.base.web.PageRequest;
import com.key.win.base.web.PageResult;
import com.key.win.base.web.Result;
import com.key.win.business.chat.eums.ImMessageTargetEnum;
import com.key.win.business.chat.eums.ImMessageTypeEnum;
import com.key.win.business.chat.model.ImMessage;
import com.key.win.business.chat.model.ImMessageDetail;
import com.key.win.business.chat.service.*;
import com.key.win.business.chat.vo.*;
import com.key.win.common.log.annotation.LogAnnotation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/chat/*")
@Api("好友相关的api")
public class ImChatCtrl {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ImFriendService imFriendService;

    @Autowired
    private ImGroupUserService imGroupUserService;

    @Autowired
    private ImMessageDetailService imMessageDetailService;

    @Autowired
    private ImChatService imChatService;

    @Autowired
    private ImMessageService imMessageService;

    @PostMapping("/findFriendMessageByPaged")
    @ApiOperation(value = "好友聊天记录分页查询")
    @LogAnnotation(module = "im", recordRequestParam = false)
    public PageResult<ImMessageChatFriendOutVo> findFriendChatByPaged(@RequestBody PageRequest<ImMessageFullVo> pageRequest) {
        PageResult<ImMessageFullVo> imMessageDetailPageResult = getImMessageDetailPageResult(pageRequest, ImMessageTargetEnum.FRIEND);
        PageResult<ImMessageChatFriendOutVo> imMessageChatFriendOutVoPageResult = getImMessageChatFriendOutVoPageResult(imMessageDetailPageResult);
        return imMessageChatFriendOutVoPageResult;
    }

    private PageResult<ImMessageChatFriendOutVo> getImMessageChatFriendOutVoPageResult(PageResult<ImMessageFullVo> imMessageDetailPageResult) {
        PageResult<ImMessageChatFriendOutVo> imMessageChatFriendOutVoPageResult = new PageResult<>();
        imMessageChatFriendOutVoPageResult.setCount(imMessageDetailPageResult.getCount());
        imMessageChatFriendOutVoPageResult.setPageNo(imMessageDetailPageResult.getPageNo());
        imMessageChatFriendOutVoPageResult.setPageSize(imMessageDetailPageResult.getPageSize());
        imMessageChatFriendOutVoPageResult.setCode(imMessageDetailPageResult.getCode());
        imMessageChatFriendOutVoPageResult.setMsg(imMessageDetailPageResult.getMsg());
        if (!CollectionUtils.isEmpty(imMessageDetailPageResult.getData())) {
            List<ImMessageChatFriendOutVo> imMessageChatFriendOutVos = new ArrayList<>();
            for (ImMessageFullVo imMessageFullVo : imMessageDetailPageResult.getData()) {
                ImMessageChatFriendOutVo imMessageChatFriendOutVo = new ImMessageChatFriendOutVo();
                imMessageChatFriendOutVo.setMessage(imMessageFullVo.getContent());
                imMessageChatFriendOutVo.setTimestamp(DateUtils.dateTimeToStr(imMessageFullVo.getCreateDate()));
                ImUserVo formUser = new ImUserVo();
                formUser.setNickName(imMessageFullVo.getNickName());
                formUser.setId(imMessageFullVo.getFromUserId());
                formUser.setAvatar("");
                imMessageChatFriendOutVo.setFromUser(formUser);
                ImUserVo toUser = new ImUserVo();
                toUser.setId(AuthenticationUtil.getUserId());
                toUser.setNickName(AuthenticationUtil.getNickName());
                imMessageChatFriendOutVo.setToUser(toUser);
                imMessageChatFriendOutVo.setContentType(imMessageFullVo.getContentType().name());
                imMessageChatFriendOutVos.add(imMessageChatFriendOutVo);
            }
            imMessageChatFriendOutVoPageResult.setData(imMessageChatFriendOutVos);
        }
        return imMessageChatFriendOutVoPageResult;
    }

    private PageResult<ImMessageChatGroupOutVo> getImMessageChatGroupOutVoPageResult(PageResult<ImMessageFullVo> imMessageDetailPageResult) {
        PageResult<ImMessageChatGroupOutVo> imMessageChatFriendOutVoPageResult = new PageResult<>();
        imMessageChatFriendOutVoPageResult.setCount(imMessageDetailPageResult.getCount());
        imMessageChatFriendOutVoPageResult.setPageNo(imMessageDetailPageResult.getPageNo());
        imMessageChatFriendOutVoPageResult.setPageSize(imMessageDetailPageResult.getPageSize());
        imMessageChatFriendOutVoPageResult.setCode(imMessageDetailPageResult.getCode());
        imMessageChatFriendOutVoPageResult.setMsg(imMessageDetailPageResult.getMsg());
        if (!CollectionUtils.isEmpty(imMessageDetailPageResult.getData())) {
            List<ImMessageChatGroupOutVo> imMessageChatGroupOutVos = new ArrayList<>();
            for (ImMessageFullVo imMessageFullVo : imMessageDetailPageResult.getData()) {
                ImMessageChatGroupOutVo imMessageChatGroupOutVo = new ImMessageChatGroupOutVo();
                imMessageChatGroupOutVo.setMessage(imMessageFullVo.getContent());
                imMessageChatGroupOutVo.setTimestamp(DateUtils.dateTimeToStr(imMessageFullVo.getCreateDate()));
                ImUserVo formUser = new ImUserVo();
                formUser.setNickName(imMessageFullVo.getNickName());
                formUser.setId(imMessageFullVo.getFromUserId());
                formUser.setAvatar("");
                imMessageChatGroupOutVo.setFromUser(formUser);
                imMessageChatGroupOutVo.setContentType(imMessageFullVo.getContentType().name());
                imMessageChatGroupOutVos.add(imMessageChatGroupOutVo);
            }
            imMessageChatFriendOutVoPageResult.setData(imMessageChatGroupOutVos);
        }
        return imMessageChatFriendOutVoPageResult;
    }

    @PostMapping("/findGroupMessageByPaged")
    @ApiOperation(value = "群组聊天记录分页查询")
    @LogAnnotation(module = "im", recordRequestParam = false)
    public PageResult<ImMessageChatGroupOutVo> findGroupChatByPaged(@RequestBody PageRequest<ImMessageFullVo> pageRequest) {
        return this.getImMessageChatGroupOutVoPageResult(getImMessageDetailPageResult(pageRequest, ImMessageTargetEnum.GROUP));
    }

    private PageResult<ImMessageFullVo> getImMessageDetailPageResult(PageRequest<ImMessageFullVo> pageRequest, ImMessageTargetEnum imMessageTargetEnum) {
        ImMessageFullVo t = pageRequest.getT();
        if (t == null) {
            t = new ImMessageFullVo();
        }
        t.setToUserId(AuthenticationUtil.getUserId());
        t.setTarget(imMessageTargetEnum);
        return imMessageDetailService.findMessageFullByPaged(pageRequest);
    }

    @GetMapping("/friend/message/top10/{targetId}")
    @ApiOperation(value = "好友聊天记录Top10")
    @LogAnnotation(module = "im", recordRequestParam = false)
    public Result<List<ImMessageChatFriendOutVo>> findFriendMessageByTop10(@PathVariable String targetId) {
        PageRequest<ImMessageFullVo> imMessageDetailPageRequest = new PageRequest<>();
        ImMessageFullVo t = new ImMessageFullVo();
        t.setTargetId(targetId);
        t.setFromUserId(targetId);
        imMessageDetailPageRequest.setT(t);
        PageResult<ImMessageChatFriendOutVo> friendChatByPaged = this.findFriendChatByPaged(imMessageDetailPageRequest);
        return Result.succeed(friendChatByPaged.getData());
    }

    @GetMapping("/group/message/top10/{targetId}")
    @ApiOperation(value = "群组聊天记录Top10")
    @LogAnnotation(module = "im", recordRequestParam = false)
    public Result<List<ImMessageChatGroupOutVo>> findGroupMessageByTop10(@PathVariable String targetId) {
        PageRequest<ImMessageFullVo> imMessageDetailPageRequest = new PageRequest<>();
        ImMessageFullVo t = new ImMessageFullVo();
        t.setTargetId(targetId);
        imMessageDetailPageRequest.setT(t);
        PageResult<ImMessageChatGroupOutVo> groupChatByPaged = this.findGroupChatByPaged(imMessageDetailPageRequest);
        return Result.succeed(groupChatByPaged.getData());
    }

    @GetMapping("/find/message/unread")
    @ApiOperation(value = "未读消息的统计")
    @LogAnnotation(module = "im", recordRequestParam = false)
    public Result<List<ImMessageNumVo>> findUnreadMessage() {
        return Result.succeed(imMessageDetailService.findUnreadMessage());
    }

    @GetMapping("/update/message/status")
    @ApiOperation(value = "更新消息状态")
    @LogAnnotation(module = "im", recordRequestParam = false)
    public Result updateImMessageStatus(@RequestBody ImMessageDetail imMessageDetail) {
        return Result.succeed(imMessageDetailService.updateMessageByStatus(imMessageDetail));
    }

    @GetMapping("/update/group/message/status/{targetId}")
    @ApiOperation(value = "更新群组未读消息状态")
    @LogAnnotation(module = "im", recordRequestParam = false)
    public Result updateGroupMessageStatus(@PathVariable String targetId) {
        ImMessageDetail imMessageDetail = new ImMessageDetail();
        imMessageDetail.setTarget(ImMessageTargetEnum.GROUP);
        imMessageDetail.setType(ImMessageTypeEnum.GROUP_NORMAL);
        imMessageDetail.setToUserId(AuthenticationUtil.getUserId());
        imMessageDetail.setTargetId(targetId);
        return Result.succeed(imMessageDetailService.updateMessageStatusByBatch(imMessageDetail));
    }

    @GetMapping("/update/friend/message/status/{fromUserId}")
    @ApiOperation(value = "更新好友未读消息状态")
    @LogAnnotation(module = "im", recordRequestParam = false)
    public Result updateFriendMessageStatus(@PathVariable String fromUserId) {
        ImMessageDetail imMessageDetail = new ImMessageDetail();
        imMessageDetail.setTarget(ImMessageTargetEnum.FRIEND);
        imMessageDetail.setType(ImMessageTypeEnum.FRIEND_NORMAL);
        imMessageDetail.setToUserId(AuthenticationUtil.getUserId());
        imMessageDetail.setTargetId(AuthenticationUtil.getUserId());
        imMessageDetail.setFromUserId(fromUserId);
        return Result.succeed(imMessageDetailService.updateMessageStatusByBatch(imMessageDetail));
    }


    @PostMapping("/friend/chat")
    @ApiOperation(value = "好友即时消息")
    @LogAnnotation(module = "im", recordRequestParam = false)
    public Result friendChat(@RequestBody ImMessageChatFriendInVo imMessageTokenVo) {
        imChatService.friendChat(imMessageTokenVo);
        return Result.succeed();
    }

    @PostMapping("/group/chat")
    @ApiOperation(value = "好友即时消息")
    @LogAnnotation(module = "im", recordRequestParam = false)
    public Result groupChat(@RequestBody ImMessageChatGroupInVo imMessageTokenVo) {
        imChatService.groupChat(imMessageTokenVo);
        return Result.succeed();
    }

    @GetMapping("/get/{id}")
    @ApiOperation(value = "获取消息详情")
    @LogAnnotation(module = "im", recordRequestParam = false)
    public Result get(@PathVariable String id) {
        return Result.succeed(imMessageDetailService.getById(id));
    }

    @GetMapping("/get/full/{id}")
    @ApiOperation(value = "获取一个完整的消息")
    @LogAnnotation(module = "im", recordRequestParam = false)
    public Result getFull(@PathVariable String id) {
        ImMessageDetail imMessageDetail = imMessageDetailService.getById(id);
        if (imMessageDetail != null) {
            ImMessageFullVo imMessageFullVo = new ImMessageFullVo();
            BeanUtils.copyProperties(imMessageDetail, imMessageFullVo);
            ImMessage imMessage = imMessageService.getById(imMessageDetail.getMessageId());
            if (imMessage != null) {
                imMessageFullVo.setContent(imMessage.getContent());
            }
        }
        return Result.succeed(imMessageDetail);
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除消息")
    @LogAnnotation(module = "im", recordRequestParam = true)
    public Result delete(@PathVariable String id) {
        return Result.result(imMessageService.deleteMessage(id));
    }

    @GetMapping("/get/all/chat")
    @ApiOperation(value = "获取所有会话列表")
    @LogAnnotation(module = "im", recordRequestParam = true)
    public Result getAllChat() throws IOException {
        return Result.succeed(imChatService.getAllChatSession());
    }

    @GetMapping("/add/{type}/{chatSessionId}")
    @ApiOperation(value = "加入指定会话中")
    @LogAnnotation(module = "im", recordRequestParam = true)
    public Result addChat(@PathVariable String type, @PathVariable String chatSessionId) {
        imChatService.addChat(ImMessageTargetEnum.getImMessageTargetEnumByName(type), chatSessionId);
        return Result.succeed();
    }

    @PostMapping("/chat")
    @ApiOperation(value = "对会话中所有在线人发送消息（除自己）")
    @LogAnnotation(module = "im", recordRequestParam = true)
    public Result sendMessageToChat(@RequestBody ImMessageChatVo imMessageChatVo) {
        imChatService.sendMessageToChat(imMessageChatVo);
        return Result.succeed();
    }

    @PostMapping("/system/msg")
    @ApiOperation(value = "获取系统消息")
    @LogAnnotation(module = "im", recordRequestParam = true)
    public Result<List<ImSystemMessageOutVo>> systemMsg() {
        List<ImSystemMessageOutVo> imSystemMessageOutVos = new ArrayList<>();
        List<ImSystemMessageFullVo> systemMessage = imMessageDetailService.findSystemMessage();
        if (!CollectionUtils.isEmpty(systemMessage)) {
            for (ImSystemMessageFullVo imSystemMessageFullVo : systemMessage) {
                ImSystemMessageOutVo imSystemMessageOutVo = new ImSystemMessageOutVo();
                imSystemMessageOutVo.setMessage(imSystemMessageFullVo.getContent());
                imSystemMessageOutVo.setTimestamp(DateUtils.dateTimeToStr(imSystemMessageFullVo.getCreateDate()));
                ImUserVo formUser = new ImUserVo();
                formUser.setNickName(imSystemMessageFullVo.getFromUserNickName());
                formUser.setId(imSystemMessageFullVo.getFromUserId());
                formUser.setAvatar("");
                imSystemMessageOutVo.setFromUser(formUser);
                ImUserVo toUser = new ImUserVo();
                toUser.setNickName(imSystemMessageFullVo.getToUserNickName());
                toUser.setId(imSystemMessageFullVo.getToUserId());
                toUser.setAvatar("");
                imSystemMessageOutVo.setToUser(toUser);
                imSystemMessageOutVo.setContentType(imSystemMessageFullVo.getContentType().name());
                imSystemMessageOutVo.setType("system");
                imSystemMessageOutVo.setId(imSystemMessageFullVo.getId());
                imSystemMessageOutVos.add(imSystemMessageOutVo);
            }
        }
        return Result.succeed(imSystemMessageOutVos);
    }
}
